<template>
  <div class="product-detail">
    <!-- 头部区域 -->
    <header class="detail-nav">
      <i class="iconfont iconfont-xiangzuo" @click="$router.go(-1)"></i>
      <div class="nav-list">
        <span :class="{'active':navIndex===0}" data-type="product" @click="scrollToView">
          <i class="iconfont icon-location iconfont-didian1" v-show="navIndex===0"></i>商品
        </span>
        <span :class="{'active':navIndex===1}" data-type="detail" @click="scrollToView">
          <i class="iconfont icon-location iconfont-didian1" v-show="navIndex===1"></i>商品详情
        </span>
        <span :class="{'active':navIndex===2}" data-type="recommend" @click="scrollToView">
          <i class="iconfont icon-location iconfont-didian1" v-show="navIndex===2"></i>商品推荐
        </span>
      </div>
      <i class="iconfont iconfont-gengduo-hengxiang"></i>
    </header>

    <!-- 轮播图 -->
    <section class="product-focus">
      <van-swipe :autoplay="3000" indicator-color="white" class="swiper-container">

        <van-swipe-item v-for="(item,index) in sliderImageList" :key="index">
          <img :src="item.imgUrl" class="swiper_img" alt="图片未找到">
        </van-swipe-item>

      </van-swipe>
    </section>

    <!-- 详情信息 -->
    <section class="detail-info">
      <p class="detail-info-name">{{productDetail.name}}</p>
      <p class="detail-info-subtitle">{{productDetail.subtitle}}</p>
      <div>
        <span class="detail-info-price">￥{{productDetail.price}}</span>
        <span class="detail-info-stock">库存{{productDetail.stock}}件</span>
      </div>
    </section>

    <!-- 商品详情 -->
    <section class="detail-content" ref="detailContent" id="content">
      <p class="detail-gap"></p>
      <ul>
        <li>概述</li>
        <li>参数</li>
        <li>安装服务</li>
        <li>常见问题</li>
      </ul>
      <div id="exp">
        <div v-html="productDetail.detail"></div>
      </div>
    </section>

    <!-- 底部导航 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" dot @click="onClickIcon" />
      <van-goods-action-icon icon="cart-o" text="购物车" badge="5" @click="onClickIcon" />
      <van-goods-action-icon icon="shop-o" text="店铺" badge="12" @click="onClickIcon" />
      <van-goods-action-button type="warning" text="加入购物车" @click="onClickButton" />
      <van-goods-action-button type="danger" text="立即购买" @click="onClickButton" />
    </van-goods-action>

    <!-- 商品规格 -->
    <van-sku v-model="show" :sku="sku" :goods="goods" :goods-id="id" :hide-stock="sku.hide_stock" :message-config="messageConfig" @buy-clicked="onBuyClicked" @add-cart="onAddCartClicked" />

  </div>
</template>

<script>
import Vue from 'vue';
import { Toast } from 'vant';
import { GoodsAction, GoodsActionIcon, GoodsActionButton } from 'vant';
import { Sku } from 'vant';
import { getProcuctDetail, submitToCar } from "../../api/index";

Vue.use(Toast);
Vue.use(GoodsAction).use(GoodsActionButton).use(GoodsActionIcon).use(Sku);

export default {
  data: function () {
    return {
      // 商品id
      id: this.$route.params.id,
      //导航索引
      navIndex: 0,
      // 保存详情数据
      productDetail: {},
      // 保存轮播图数据
      sliderImageList: [],

      show: false,
      sku: {
        tree: [{
          k: '颜色', // skuKeyName：规格类目名称
          v: [],
          k_s: 's1' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
        }],
        list: [],
        price: 100, // 默认价格（单位元）
        stock_num: "100", // 商品总库存
        collection_id: 2259, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
      },
      goods: {
        // 商品标题
        title: '测试商品',
        // 默认商品 sku 缩略图
        picture: 'https://b.yzcdn.cn/vant/sku/shoes-1.png'
      },
      messageConfig: {
        // 图片上传回调，需要返回一个promise，promise正确执行的结果需要是一个图片url
        uploadImg: () => {
          return new Promise((resolve) => {
            setTimeout(() => resolve('https://img01.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg'), 1000);
          });
        },
        // 可选项，自定义图片上传逻辑，使用此选项时，会禁用原生图片选择
        customUpload: () => {
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve('https://img01.yzcdn.cn/vant/leaf.jpg');
            }, 1000);
          });
        },
        // 最大上传体积 (MB)
        uploadMaxSize: 3,
        // placeholder 配置
        placeholderMap: {
          text: 'xxx',
          tel: 'xxx',
        },
        // 初始留言信息
        // 键：留言 name
        // 值：留言内容
        initialMessages: {
          留言: '留言信息'
        }
      }
    }
  },
  methods: {
    // 导航选择
    scrollToView(e) {
      let $type = e.target.getAttribute('data-type')
      switch ($type) {
        case 'product':
          this.navIndex = 0
          break
        case 'detail':
          this.navIndex = 1
          break
        case 'recommend':
          this.navIndex = 2
          break
      }
    },
    // 获取商品详情
    fetchProductDetail() {
      const params = {
        id: this.id
      }
      getProcuctDetail(params).then(res => {
        this.productDetail = res;

        let tempId=this.id;

        // 解析商品轮播图url
        let subImages = res.subImages.split(',')
        let imageHost = res.imageHost
        subImages.forEach((item) => {
          this.sliderImageList.push({
            imgUrl: imageHost + item
          })

          // 填充sku
          this.sku.tree[0].v.push({
            id: ++tempId, // skuValueId：规格值 id
            name: this.getRandCN(3) + '式', // skuValueName：规格值名称
            imgUrl: imageHost + item, // 规格类目图片，只有第一个规格类目可以定义图片
            previewImgUrl: imageHost + item, // 用于预览显示的规格类目图片
          });

          this.sku.list.push({
            id: tempId, // skuId，下单时后端需要
            s1: tempId, // 规格类目 k_s 为 s1 的对应规格值 id
            price: this.productDetail.price * 100, // 价格（单位分）
            stock_num: parseInt(this.productDetail.stock) // 当前 sku 组合对应的库存
          });
        })

        this.sku.price = this.productDetail.price;
        this.sku.stock_num = parseInt(this.productDetail.stock);
        this.goods.picture = this.sliderImageList[0].imgUrl;
      })
    },
    // 生成随机汉字(商品规格)
    getRandCN(len) {
      let min = Math.ceil(19968);
      let max = Math.floor(40917);
      let str = '';
      for (let i = 0; i < len; i++) {
        let n = Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值
        str += String.fromCharCode(n);
      }
      return str;
    },
    // 商品规格
    onBuyClicked() {
      console.log('onBuyClicked')
    },
    // 加入购物车
    onAddCartClicked() {
      const params = {
        productId: this.id,
        count: 1
      }

      submitToCar(params).then(res => {
        if (res.status === 0) {
          Toast(res.msg);
        } else {
          Toast('商品ID不存在');
        }
      })
    },
    addToCar() {
      this.show = true
    },
    onClickIcon() {
      Toast('点击图标');
    },
    onClickButton() {
      this.show = true;
    },
  },
  mounted: function () {
    this.fetchProductDetail()
  },
  updated: function () {
    //   因为获取到的是html，还加上了内嵌宽高，所以在这里手动修改一下图片的宽高
    let exp = document.querySelector('#exp');
    let imgs = document.querySelectorAll('#exp img');
    imgs.forEach(item => {
      item.setAttribute('width', exp.clientWidth + 'px')
      item.removeAttribute('height');
    })
  }
}
</script>

<style lang="scss" scoped>
@import "../../common/style/mixin.scss";
// 头部
.product-detail {
  width: 100%;

  .detail-nav {
    @include fj;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 88px;
    padding: 0 20px;
    line-height: 88px;
    box-sizing: border-box;
    z-index: 1000;
    color: #252525;
    background: #fff;
    border-bottom: 1px solid #dcdcdc;

    i {
      font-size: 50px;
      color: #000;
    }

    div span {
      padding: 0 20px;
      font-size: 28px;

      &.active {
        color: $red;
      }

      .iconfont {
        padding-right: 8px;
        font-size: 28px;
        color: $red;
      }
    }
  }
}

// 轮播图
.product-focus {
  margin-top: 88px;

  .swiper-container {
    .swiper_img {
      width: 100%;
      height: 700px;
    }
  }
}

// 详情信息
.detail-info {
  width: 100%;
  padding: 20px 30px;
  font-size: 30px;
  box-sizing: border-box;

  .detail-info-name {
    font-size: 40px;
    color: #333;
  }

  .detail-info-subtitle {
    text-align: left;
    padding: 10px 0;
    font-size: 28px;
    color: #999;
  }

  div {
    @include fj;
    height: 70px;
    line-height: 80px;
    padding: 10px 0;
    font-size: 32px;
    color: #999;

    .detail-info-price {
      color: $red;
      font-size: 44px;
    }
  }
}

// 商品详情
.detail-content {
  width: 100%;

  .detail-gap {
    width: 100%;
    height: 20px;
    background: #eee;
  }

  ul {
    @include fj;
    width: 100%;
    margin: 20px 0;

    li {
      flex: 1;
      padding: 10px 0;
      text-align: center;
      font-size: 30px;
      border-right: 1px solid #999;
      box-sizing: border-box;

      &:last-child {
        border-right: none;
      }
    }
  }

  div {
    width: 100%;
    overflow: hidden;

    p {
      width: 100%;
      font-size: 40px;
      text-align: center;

      img {
        width: 100px !important;
        height: 100%;
      }
    }
  }
}
</style>